package com.syn.synold4s.vm;
import android.app.Application;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import com.gaoyi.basemodule.apiresult.ApiResultData;
import com.gaoyi.basemodule.baseCallback.OnResultListener;
import com.gaoyi.basemodule.baseUtil.SPUtil;
import com.gaoyi.basemodule.baseUtil.ToastUtil;
import com.gaoyi.basemodule.basebean.LoginDto;
import com.gaoyi.basemodule.basebean.ProjectDto;
import com.gaoyi.basemodule.basebean.UserDto;
import com.gaoyi.basemodule.baseconstant.ApiStatus;
import com.gaoyi.basemodule.baseconstant.Constants;
import com.gaoyi.basemodule.baseconstant.SPName;
import com.gaoyi.basemodule.basevm.BaseViewModel;
import com.google.gson.reflect.TypeToken;
import com.syn.synold4s.R;
import com.syn.synold4s.activity.MainActivity;
import com.syn.synold4s.activity.ProjectSelectionActivity;
import com.syn.synold4s.bean.query.LoginQuery;
import com.syn.synold4s.repository.UserRepository;
import com.syn.synold4s.util.RSAUtil;
import java.util.Map;

public class LoginViewModel extends BaseViewModel {

    MutableLiveData<String> mAccount;
    MutableLiveData<String> mPwd;
    final UserRepository mRepository;

    public LoginViewModel(@NonNull Application application) {
        super(application);
        mRepository = new UserRepository();
    }

    public MutableLiveData<String> getAccount() {
        if (mAccount == null) {
            mAccount = new MutableLiveData<>();
        }
        return mAccount;
    }

    public void setAccount(String account) {
        mAccount = new MutableLiveData<>();
        mAccount.setValue(account);
    }

    public MutableLiveData<String> getPwd() {
        if (mPwd == null) {
            mPwd = new MutableLiveData<>();
        }
        return mPwd;
    }

    public void setPwd(String pwd) {
        mPwd = new MutableLiveData<>();
        mPwd.setValue(pwd);
    }

    public void login(boolean isRemPwd) {
        LoginQuery bean = new LoginQuery();
        bean.setUserName(mAccount.getValue());
        bean.setPassword(mPwd.getValue());
        mRepository.login(bean, new OnResultListener() {
            @Override
            public void onSuccess(Object apiResult) {
                ApiResultData<LoginDto> apiResultData = (ApiResultData<LoginDto>) apiResult;
                LoginDto data = apiResultData.getData();
                if (apiResultData.getStatus() != ApiStatus.SUCCESS) {
                    if (apiResultData.getStatus() == 1000 && data != null &&
                            data.getPublicKey() != null && !data.getPublicKey().isEmpty()) {
                        login(isRemPwd);
                        return;
                    }
                    if (getView() != null) {
                        getView().hideLoading();
                    }
                    mResultCode.setValue(apiResultData.getStatus());
                    ToastUtil.showToast(apiResultData.getMessage());
                    return;
                }
                if (getView() != null) {
                    getView().hideLoading();
                }
                mResultCode.setValue(apiResultData.getStatus());
                ToastUtil.showToast(apiResultData.getMessage());
                UserDto userInfo = data.getUserInfo();
                if (isRemPwd) {
                    Map<Integer, String> key = RSAUtil.getKey();
                    if (!key.isEmpty()) {
                        String encipherPwd = RSAUtil.encipher(mPwd.getValue(), key.get(0));
                        encipherPwd += Constants.SPLIT + key.get(1);
                        SPUtil.getInstance().putString(SPName.PASSWORD, encipherPwd);
                    } else {
                        SPUtil.getInstance().putString(SPName.PASSWORD, "");
                    }
                } else {
                    SPUtil.getInstance().putString(SPName.PASSWORD, "");
                }
                SPUtil.getInstance().putString(SPName.ACCOUNT, userInfo.getUserName());
                SPUtil.getInstance().putString(SPName.ID, userInfo.getId());
                int jumpFlag = SPUtil.getInstance().getInt(SPName.JUMP_FLAG, -1);
                if (-1 == jumpFlag) {
                    SPUtil.getInstance().putString(SPName.TOKEN,
                            data.getToken() == null ? "" : data.getToken());
                } else {
                    SPUtil.getInstance().putString(SPName.NEW_TOKEN,
                            data.getToken() == null ? "" : data.getToken());
                }
                SPUtil.getInstance().putString(SPName.REFRESH_TOKEN,
                        data.getRefreshToken() == null ? "" : data.getRefreshToken());
                ProjectDto proj = userInfo.getProj();
                if (proj == null) {
                    SPUtil.getInstance().putString(SPName.PROJ_ID, "");
                    SPUtil.getInstance().putString(SPName.PROJ_CODE, "");
                    SPUtil.getInstance().putString(SPName.PROJ_NAME, "");
                    SPUtil.getInstance().putString(SPName.PROJ_ADDRESS, "");
                } else {
                    SPUtil.getInstance().putString(SPName.PROJ_ID, proj.getId());
                    SPUtil.getInstance().putString(SPName.PROJ_CODE, proj.getCode());
                    SPUtil.getInstance().putString(SPName.PROJ_NAME, proj.getName());
                    SPUtil.getInstance().putString(SPName.PROJ_ADDRESS, proj.getAddress());
                    SPUtil.getInstance().putString(SPName.PROJ_LAT, proj.getLat());
                    SPUtil.getInstance().putString(SPName.PROJ_LNG, proj.getLng());
                }
                Intent intent;
//                if (0 == jumpFlag || 1 == jumpFlag) {//loginToken为空；选择项目页再次回到登录页；
//                    SPUtil.getInstance().putBoolean(SPName.LOGIN_FLAG, true);
//                    SPUtil.getInstance().putBoolean(SPName.TOKEN_FLAG, true);
//                    intent = new Intent(mApplication, MainActivity.class);
//                } else {//正常登录流程；进入选择项目页
//                    SPUtil.getInstance().putBoolean(SPName.TOKEN_FLAG, false);
//                    intent = new Intent(mApplication, ProjectSelectionActivity.class);
//                }
                intent = new Intent(mApplication, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                mApplication.startActivity(intent);
            }

            @Override
            public void onFails(Exception e) {
                e.printStackTrace();
                if (getView() != null) {
                    getView().hideLoading();
                }
                mResultCode.setValue(ApiStatus.NET_ERROR);
                ToastUtil.showToast(R.string.network_error);
            }
        }, new TypeToken<ApiResultData<LoginDto>>() {
        }.getType());
    }

//    public void forgotPwd() {
//        mRepository.forgotPwd(mEmail.getValue(), new OnResultListener() {
//            @Override
//            public void onSuccess(Object apiResult) {
//                ApiResultData<String> apiResultData = (ApiResultData<String>) apiResult;
//                mForgotPwdCode.setValue(apiResultData.getStatus());
//                if (apiResultData.getStatus() == ApiStatus.SUCCESS) {
//                    ToastUtil.showToast(R.string.send_success);
//                } else {
//                    ToastUtil.showToast(apiResultData.getMessage());
//                }
//            }
//
//            @Override
//            public void onFails(Exception e) {
//                mForgotPwdCode.setValue(ApiStatus.NET_ERROR);
//                ToastUtil.showToast(R.string.network_error);
//            }
//        }, new TypeToken<ApiResultData<String>>() {
//        }.getType());
//    }
//
//    public void resetPwd() {
//        ResetPwdQuery bean = new ResetPwdQuery();
//        bean.setEmail(mEmail.getValue());
//        bean.setNewPassWord(mNewPwd.getValue());
//        bean.setConfirmPassword(mConfirmPwd.getValue());
//        mRepository.resetPwd(bean, new OnResultListener() {
//            @Override
//            public void onSuccess(Object apiResult) {
//                ApiResultData<String> apiResultData = (ApiResultData<String>) apiResult;
//                mResetPwdCode.setValue(apiResultData.getStatus());
//                ToastUtil.showToast(apiResultData.getMessage());
//            }
//
//            @Override
//            public void onFails(Exception e) {
//                mResetPwdCode.setValue(ApiStatus.NET_ERROR);
//                ToastUtil.showToast(R.string.network_error);
//            }
//        }, new TypeToken<ApiResultData<String>>() {
//        }.getType());
//    }
}
